<template>
    <div>
      <h1>上传驱动文件</h1>
      <el-form ref="uploadForm" :model="formData" label-width="120px">
        <el-form-item label="硬件类型" prop="hardware_type">
          <el-select v-model="formData.hardware_type" placeholder="请选择">
            <el-option
              v-for="item in hardwareType"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="包名" prop="package_name">
          <el-input v-model="formData.package_name"></el-input>
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model="formData.version"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description"></el-input>
        </el-form-item>

        <el-form-item label="请选择硬件类型" prop="description">
          <!-- usb，pci，单选 -->
          <el-radio v-model="deviceType" label="pci">pci</el-radio>
  <el-radio v-model="deviceType" label="usb">usb</el-radio>
        </el-form-item>
        <el-form-item label="适用的PCI硬件" prop="pci_vendor" v-show='deviceType=="pci"'>
            <el-select
              v-model="formData.pci_vendor"
      
              filterable
              remote
              reserve-keyword
              placeholder="请输入PCI厂商信息"
              :remote-method="pciRemoteMethod"
              @change="remotePciDeviceMethod"
              :loading="loading">
              <el-option
                v-for="item in pci_options"
                :key="item.value"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>

          <el-select
            v-model="formData.device_id"
            
            filterable
            
            reserve-keyword
            placeholder="请输入PCI硬件信息"
            
            :loading="loading">
            <el-option
              v-for="item in pci_device_options"
              :key="item.id"
              :label="item.device_name"
              :value="item.id">
            </el-option>
          </el-select>
      </el-form-item>
        <el-form-item label="适用的USB硬件" prop="usb_vendor" v-show='deviceType=="usb"'>
            <el-select
              v-model="formData.usb_vendor"
              
              filterable
              remote
              reserve-keyword
              placeholder="请输入USB厂商信息"
              :remote-method="usbRemoteMethod"
              @change="remoteUsbDeviceMethod"
              :loading="loading">
              <el-option
                v-for="item in usb_options"
                :key="item.value"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
            <el-select
            v-model="formData.device_id"
            
            filterable
            remote
            reserve-keyword
            placeholder="请输入USB硬件信息"
            
            :loading="loading">
            <el-option
              v-for="item in usb_device_options"
              :key="item.id"
              :label="item.device_name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="适用的系统版本" prop="system_version">
          <el-select
          v-model="formData.system_version"
          multiple
          filterable
          allow-create
          remote
          reserve-keyword
          placeholder="请输入关键词或添加新条目"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        </el-form-item> -->
        <el-form-item label="文件" prop="driver_file">
            <el-upload
            class="upload-demo"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-success="handleSuccess"
            :on-error="handleError"
            name="driver_file"
            :action="'/api/upload_driver/'" 
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          
            <div v-if="fileToUpload">{{ fileToUpload.name }}</div>
            <div v-if="uploadedFileSize">已上传文件大小: {{ fileToUpload.size }}</div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button @click="handleReset">重置</el-button>
        </el-form-item>
          <el-form-item v-if="uploadProgress !== null">
            <el-progress :percentage="uploadProgress" />
          </el-form-item>
        </el-form>
      </div>
    </template>
  
  <script>
    import axios from 'axios'; 
    import { getPci,getUsb } from '../api';
export default {
    data() {
        return {
          deviceType:'',
          pci_device_options:[],
          usb_device_options:[],
          device_id:'',
          uploadedFileSize: null,
        formData: {
          file_name:"",
          package_name:"",
          version:"",
          file_size:"",
          description:"",
          hardware_id:"",
          hardware_type_id:"",
          pci_usb_key:"",
          device_id:""
        },
        hardwareType:[
          {
            value: 'VGA',
            label: '显卡'
          },
          {
            value: 'Network',
            label: '网卡'
          },
          {
            value: 'Sound',
            label: '声卡'
          },
          {
            value: 'Printer',
            label: '打印机'
          },
          {
            value: 'Camera',
            label: '摄像头'
          },          
          {
            value: 'Bluetooth',
            label: '蓝牙'
          },
          {
            value: 'Keyboard',
            label: '键盘'
          },
          {
            value: 'Mouse',
            label: '鼠标'
          },

          {
            value: 'Scanner',
            label: '扫描仪'
          },
      ],
        fileToUpload: null,
        uploadProgress: null,
        system_options: [],
        pci_options: [], 
        usb_options: [], 
        pciApiUrl: '/api/searchPciVendor?query=',
        usbApiUrl: '/api/searchUsbVendor?query=',
        pciDeviceUrl:'/api/getPciHardwareByVendor',
        usbDeviceUrl:'/api/getUsbHardwareByVendor',
        loading: false,
        pcioptions:[], 
        usboptions:[],
        value: [],
        loading: false,
        };
        
    },
    methods: {
    pciRemoteMethod(query) {
      // Triggered on input change
      this.pciFetchData(query);
    },
    usbRemoteMethod(query) {
      // Triggered on input change
      this.usbFetchData(query);
    },
    async remotePciDeviceMethod(query) {
      let that=this;
      let {data}=await axios({method:'get',url:that.pciDeviceUrl,params:{vendor:query}})
that.pci_device_options=data;
    },
    async remoteUsbDeviceMethod(query) {
      let that=this;
      let {data}=await axios({method:'get',url:that.usbDeviceUrl,params:{vendor:query}})
that.usb_device_options=data;
    },
    pciFetchData(query) {
      if (query !== '') {
        this.loading = true;
        axios.get(`${this.pciApiUrl}${query}`) // 使用导入的 axios 实例
          .then(response => {
            this.loading = false;
            this.pci_options = response.data.map(item => {
              return { value: item.value, label: item.label };
            });
          })
          .catch(error => {
            console.error('Error fetching data:', error);
            this.loading = false;
          });
      } else {
        this.pci_options = [];
      }
    },

    usbFetchData(query) {
      if (query !== '') {
        this.loading = true;
        axios.get(`${this.usbApiUrl}${query}`) // 使用导入的 axios 实例
          .then(response => {
            this.loading = false;
            this.usb_options = response.data.map(item => {
              return { value: item.value, label: item.label };
            });
          })
          .catch(error => {
            console.error('Error fetching data:', error);
            this.loading = false;
          });
      } else {
        this.usb_options = [];
      }
    },

      handleBeforeUpload(file) {
        this.fileToUpload = file;
        return false; // 阻止 el-upload 自动上传
      },
      async handleSubmit() {
        this.$refs['uploadForm'].validate(async (valid) => {
          if (valid) {
            // 通过表单校验，执行提交逻辑
            const formData1 = new FormData();
            formData1.append('package_name', this.formData.package_name);
            formData1.append('version', this.formData.version);
            formData1.append('description', this.formData.description);
            formData1.append('file_size', this.fileToUpload.size); 
            formData1.append('file_name', this.fileToUpload.name);
            // if (this.formData.description === 'usb') {
            //   this.device_id= this.usb_device_options;
            // }else{
            //   this.device_id= this.pci_device_options;
            // }
            //this.device_id=this.deviceType;
            let deviceId=this.formData.device_id;
            formData1.append('hardware_id',deviceId);
            formData1.append('hardware_type_id',this.formData.hardware_type);
            formData1.append('pci_usb_key', this.deviceType);
            formData1.append('driver_file', this.fileToUpload);
            formData1.append('device_id', deviceId);
            console.log('表单数据:', this.formData1);

            try {
              const response = await axios.post('/api/upload_driver', formData1, {
                headers: {
                  'Content-Type': 'multipart/form-data',
                },
                onUploadProgress: (progressEvent) => {
                  const percentCompleted = Math.round(
                    (progressEvent.loaded * 100) / progressEvent.total
                  );
                  this.uploadProgress = percentCompleted; // 更新上传进度
                },
              });

              console.log(response.data); // 处理上传成功后的逻辑
              this.$message.success('文件上传成功');
            } catch (error) {
              console.error(error); // 处理上传失败的情况
              this.$message.error('文件上传失败');
            }
          } else {
            this.$message.error('请填写完整的信息并上传文件');
          }
        });
      },
      handleSuccess(response, file, fileList) {
        // 处理上传成功后的逻辑
      },
      handleError(err) {
        // 处理上传失败后的逻辑
      },
      handleReset() {
        this.$refs['uploadForm'].resetFields(); // 重置表单
        this.uploadProgress = null; // 重置上传进度
      },

    
  },
    mounted() {
      // this.fetchPcioptions();
      // this.fetchData('');
    },
    rules: {
      hardware_type: [{ required: true, message: '请输入硬件类型', trigger: 'blur' }],
      package_name: [{ required: true, message: '请输入包名', trigger: 'blur' }],
      version: [{ required: true, message: '请输入版本', trigger: 'blur' }],
      size: [{ required: true, message: '请输入大小', trigger: 'blur' }],
      description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
      applicable_devices: [{ required: true, message: '请输入适用硬件', trigger: 'blur' }],
    },
  };
  </script>
  